package org.theSeed.springDatasouceProp.contract.impl;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.theSeed.springDatasouceProp.contract.BaseDataSourceClose;
import org.theSeed.springDatasouceProp.pojo.SeedBaseDataSourceHolder;

@Slf4j
@Component
public class BaseDataSourceCloseImpl implements BaseDataSourceClose<AutoCloseable> {
    @Autowired
    private SeedBaseDataSourceHolder seedBaseDataSourceHolder;

    @Override
    public boolean canDoIt(Class clazz) {
        return AutoCloseable.class.isAssignableFrom(clazz);
    }

    @SneakyThrows
    @Override
    public void closeDataSource(Object ds) {
        try {
            ((AutoCloseable)ds).close();
        } catch (Exception e) {
            String name = seedBaseDataSourceHolder.getDataSourceMap()
                    .entrySet()
                    .stream()
                    .filter(item -> item.getValue().equals(ds))
                    .map(item -> item.getKey())
                    .findFirst().orElse(null);
            log.error("数据源名称{}为关闭失败",name);
            throw e;
        }
    }
}
